package com.spzx.gateway.filter;

import java.nio.charset.StandardCharsets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.html.EscapeUtil;
import com.spzx.gateway.config.properties.XssProperties;
import io.netty.buffer.ByteBufAllocator;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 跨站脚本过滤器，用于防止XSS攻击。
 * 该过滤器会根据配置对特定的HTTP请求进行处理，确保请求体中的内容不会包含恶意脚本。
 *
 * @author spzx
 */
@Component
@ConditionalOnProperty(value = "security.xss.enabled", havingValue = "true")
public class XssFilter implements GlobalFilter, Ordered {

    /**
     * 注入的XSS配置属性，用于控制XSS过滤器的行为。
     */
    @Autowired
    private XssProperties xss;

    /**
     * 过滤器的核心逻辑，处理传入的HTTP请求。
     *
     * @param exchange 当前的HTTP交换对象，包含请求和响应信息。
     * @param chain    过滤器链，用于继续传递请求到下一个过滤器或目标服务。
     * @return 返回一个Mono<Void>表示异步操作的结果。
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        // 如果XSS过滤未启用，则直接放行请求
        if (!xss.getEnabled()) {
            return chain.filter(exchange);
        }

        // 对于GET和DELETE请求不进行过滤
        HttpMethod method = request.getMethod();
        if (method == null || method == HttpMethod.GET || method == HttpMethod.DELETE) {
            return chain.filter(exchange);
        }

        // 只对JSON类型的请求进行过滤
        if (!isJsonRequest(exchange)) {
            return chain.filter(exchange);
        }

        // 如果请求的URL在排除列表中，则不进行过滤
        String url = request.getURI().getPath();
        if (StringUtils.matches(url, xss.getExcludeUrls())) {
            return chain.filter(exchange);
        }

        // 创建装饰后的请求对象，用于修改请求体
        ServerHttpRequestDecorator httpRequestDecorator = requestDecorator(exchange);
        return chain.filter(exchange.mutate().request(httpRequestDecorator).build());
    }

    /**
     * 创建并返回一个装饰后的ServerHttpRequest对象，用于修改原始请求体。
     *
     * @param exchange 当前的HTTP交换对象，包含请求和响应信息。
     * @return 返回一个装饰后的ServerHttpRequest对象。
     */
    private ServerHttpRequestDecorator requestDecorator(ServerWebExchange exchange) {
        return new ServerHttpRequestDecorator(exchange.getRequest()) {
            @Override
            public Flux<DataBuffer> getBody() {
                // 获取原始请求体，并对其进行XSS过滤
                return super.getBody().buffer().map(dataBuffers -> {
                    DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                    DataBuffer join = dataBufferFactory.join(dataBuffers);
                    byte[] content = new byte[join.readableByteCount()];
                    join.read(content);
                    DataBufferUtils.release(join);

                    // 将字节数组转换为字符串，并使用EscapeUtil进行XSS过滤
                    String bodyStr = new String(content, StandardCharsets.UTF_8);
                    bodyStr = EscapeUtil.clean(bodyStr);

                    // 将过滤后的字符串重新转换为字节数组，并创建新的DataBuffer对象
                    byte[] bytes = bodyStr.getBytes(StandardCharsets.UTF_8);
                    NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
                    DataBuffer buffer = nettyDataBufferFactory.allocateBuffer(bytes.length);
                    buffer.write(bytes);
                    return buffer;
                });
            }

            @Override
            public HttpHeaders getHeaders() {
                // 修改请求头，删除原有的Content-Length并设置Transfer-Encoding为chunked
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.putAll(super.getHeaders());
                httpHeaders.remove(HttpHeaders.CONTENT_LENGTH);
                httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
                return httpHeaders;
            }
        };
    }

    /**
     * 判断当前请求是否为JSON类型的请求。
     *
     * @param exchange HTTP交换对象，包含请求和响应信息。
     * @return 如果是JSON请求则返回true，否则返回false。
     */
    public boolean isJsonRequest(ServerWebExchange exchange) {
        String header = exchange.getRequest().getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        return StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE);
    }

    /**
     * 定义过滤器的执行顺序，数值越小优先级越高。
     *
     * @return 返回过滤器的顺序值。
     */
    @Override
    public int getOrder() {
        return -100;
    }
}
